<template>
    <div class="container-fluid p-4">
        <el-row justify="center">
            <el-col :xs="24" :sm="20" :md="16" :lg="12">
                <el-card shadow="never">
                    <template #header>
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">个人信息</h5>
                            <div>
                                <el-button v-if="!isEditing" type="primary" :icon="Edit" @click="toggleEdit(true)">
                                    编辑
                                </el-button>
                                <template v-else>
                                    <el-button @click="toggleEdit(false)">取消</el-button>
                                    <el-button type="success" :loading="isLoading" @click="saveProfile">
                                        保存
                                    </el-button>
                                </template>
                            </div>
                        </div>
                    </template>

                    <el-form :model="profileForm" :rules="profileRules" ref="formRef" label-position="top"
                        :disabled="!isEditing">

                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="profileForm.name" placeholder="请输入姓名"></el-input>
                        </el-form-item>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="年龄" prop="age">
                                    <el-input-number v-model="profileForm.age" :min="1" :max="150" placeholder="请输入年龄"
                                        style="width: 100%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="角色" prop="role">
                                    <el-input v-model="profileForm.role" disabled placeholder="用户角色"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-form-item label="电子邮箱" prop="email">
                            <el-input v-model="profileForm.email" placeholder="请输入电子邮箱"></el-input>
                        </el-form-item>

                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="profileForm.phone" placeholder="请输入手机号"></el-input>
                        </el-form-item>
                    </el-form>
                    <div class="danger-zone">
                        <h6 class="text-danger">危险操作</h6>
                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <div>
                                <strong>修改密码</strong>
                                <p class="text-muted small mb-0">定期修改密码可以提高账户安全性。</p>
                            </div>
                            <el-button @click="changePasswordModalVisible = true">修改密码</el-button>
                        </div>
                        <el-divider />
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong>注销账户</strong>
                                <p class="text-muted small mb-0">注销后，您的所有数据将被永久删除且无法恢复。</p>
                            </div>
                            <el-button type="danger" plain @click="handleCancelAccount">注销账户</el-button>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
    <ChangePasswordModal v-model="changePasswordModalVisible" />
</template>

<script setup>
import { ref, reactive, onMounted} from 'vue';
import { useUserStore } from '@/stores/user.js';
import { ElMessage,ElMessageBox } from 'element-plus';
import { Edit } from '@element-plus/icons-vue';
import ChangePasswordModal from '@/components/alert/common/ChangePasswordModal.vue'; // 确保路径正确
import { Key, CircleClose } from '@element-plus/icons-vue';
import router from '@/router/index.js';
const userStore = useUserStore();
const formRef = ref(null);

const isEditing = ref(false);
const isLoading = ref(false);
const changePasswordModalVisible = ref(false);
// 用于表单绑定的响应式对象
const profileForm = reactive({
    username: '',
    name: '',
    age: undefined,
    email: '',
    phone: '',
    role: '',
});

// 表单校验规则
const profileRules = {
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
    email: [
        { required: true, message: '电子邮箱不能为空', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
    ]
};

// 将 store 中的数据映射到表单
const syncFormWithStore = () => {
    const user = userStore.user;
    if (user) {
        profileForm.name = user.name;
        profileForm.age = user.age;
        profileForm.email = user.email;
        profileForm.phone = user.phone;

        // 将 roleId 转换为可读的角色名称
        const roleMap = { 1: '管理员', 2: '导师', 3: '学员' };
        profileForm.role = roleMap[user.roleId] || '未知角色';
    }
};

// 切换编辑模式
const toggleEdit = (editMode) => {
    isEditing.value = editMode;
    // 如果是取消编辑，则将表单数据重置为 store 中的原始数据
    if (!editMode) {
        syncFormWithStore();
    }
};

// 保存个人信息
const saveProfile = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();
        isLoading.value = true;

        // 准备要发送给后端的数据
        const payload = {
            name: profileForm.name,
            age: profileForm.age,
            email: profileForm.email,
            phone: profileForm.phone,
        };

        // 调用 store 中的 action
        userStore.modifyBasicInfo(payload,
            () => { // 成功回调
                isEditing.value = false; // 关闭编辑模式
                isLoading.value = false;
                // 重新同步一下表单数据，以防后端有其他处理
                syncFormWithStore();
            },
            () => { // 失败回调
                isLoading.value = false;
            }
        );

    } catch (error) {
        ElMessage.error('表单校验失败，请检查您的输入。');
    }
};
const handleCancelAccount = () => {
    // 调用 store 中的注销账户 action，它内部已经包含了确认弹窗
    userStore.cancelAccount();
    //router.push('/login');
};
// 组件挂载时，用 store 中的数据初始化表单
onMounted(() => {
    syncFormWithStore();
});
</script>

<style scoped>
.el-form-item {
    margin-bottom: 22px;
}

.danger-zone {
    padding: 1rem;
    background-color: #fef0f0;
    border: 1px solid #fde2e2;
    border-radius: 4px;
}
</style>